import pymysql

from config import IHRMDB


class DBUtil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host=IHRMDB.HOST, port=IHRMDB.PORT, user=IHRMDB.USER, password=IHRMDB.PASSWORD,
                                       database=IHRMDB.DATABASE, charset=IHRMDB.CHARSET)
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_one(cls, sql):
        cursor = None
        result = None
        try:
            # 创建数据库连接
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 获取第一条数据
            result = cursor.fetchone()
        except Exception as e:
            print(e)
            raise e
        # 关闭游标
        finally:
            if cursor:
                cursor.close()
            # 关闭数据库连接对象
            cls.__close_conn()
            return result

    @classmethod
    def uid_db(cls, sql):
        conn = None
        cursor = None
        try:
            # 创建数据库连接
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行sql
            cursor.execute(sql)
            # 手动提交
            conn.commit()
        except Exception as e:
            print(e)
            if conn:
                conn.rollback()
            raise e
        finally:
            # 关闭游标
            if cursor:
                cursor.close()
            # 关闭数据库连接对象
            cls.__close_conn()


if __name__ == '__main__':
    data = DBUtil.select_one("SELECT * from t_book;")
    print(data)

    # DBUtil.uid_db("insert into t_book (id, title, pub_date) values(12, '接口测试', '2021-09-09');")
